import { QueryBean } from '@indexea/sdk';
import { SearchContext } from '@indexea/sdk/context';
import { useCallback, useEffect, useState } from 'react';
import { useIndexeaSearch } from '../hooks';

export type QueriesProps = {
  context: SearchContext,
}

/**
 * 显示切换不同查询的 Tab 菜单
 * @param props
 */
export default function () {
  const { context, layout: { indices }, results, search } = useIndexeaSearch();

  const onClick = useCallback((q: string, id?: number) => (e: React.MouseEvent) => {
    e.preventDefault();
    if (context.query !== id) {
      search(q, id);
    }
  }, [context, search]);

  return (
    <ul className="nav nav-tabs ps-3 mt-3">
      {context?.widget?.queries?.map((query: QueryBean) => (
        <li className="nav-item" key={query.id}>
          <a
            href={`?q=${context.q}&i=${query.id}`}
            onClick={onClick(context.q, query.id)}
            className={
              query.id == context?.query ? 'nav-link active' : 'nav-link'
            }
          >
            {indices['label' + query.id] || query.name}
            {indices.show_count && (
              // @ts-ignore id and results?.results
              <Count id={query.id} count={results?.results[query.id + '']}/>
            )}
          </a>
        </li>
      ))}
    </ul>
  );
}

type CountProps = {
  id: number | string,
  count?: number,
}

const refValues: Record<number | string, number> = {};

// 尽可能只一路向前，不 reset 回0
function Count({ id, count }: CountProps) {
  const [value, setValue] = useState(refValues[id] || 0);

  useEffect(() => {
    if (count != null) {
      refValues[id] = count;
      setValue(count);
    }
  }, [count]);

  return (
    <span className="badge bg-light text-dark rounded-pill fw-light">
      {value}
    </span>
  );
}
